<template>
  <div class="pad-20 bgc-default">
    <!-- 平台类型 -->
    <third-platform-head @platformTypeChange="platformTypeChange"></third-platform-head>

    <div class="bg-color-white mar-t-15 pad-l-20 pad-r-20">
      <div v-if="!loginMemberId" class="pad-t-15">
        <el-tabs v-model="shopType" @tab-click="doChangeTab">
          <el-tab-pane label="企业店铺" name="2"></el-tab-pane>
          <el-tab-pane label="分销店铺" name="1"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="mar-t-5">
        <template v-if="(loginMemberId && shopType == 1) || (this.getEnterpriseId() && shopType == 2)">
          <el-button type="primary" @click="doAddShop">添加店铺</el-button>
        </template>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default mar-t-20">
        <div class="search-item">
          <label>搜索店铺：</label>
          <el-input style="width:200px;" v-model="searchListQuery.shopName" placeholder="请输入店铺名称"></el-input>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container mar-t-15">
        <el-table :data="dataList" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column label="店铺名称" prop="shopName"></el-table-column>
          <el-table-column key='1' label="店主" v-if="shopType === '1'" align="left">
            <template slot-scope="scope">
              <div class="flex v-align-c" v-if="scope.row.member" @click="doEdit(scope.row)">
                <label><img v-if="scope.row.member.avatar" :src="scope.row.member.avatar" class="user-avatar" /></label>
                <div class="font-14 pad-l-10">
                  <div>昵称：{{scope.row.member.nickname||''}}</div>
                  <div>姓名：{{scope.row.member.realName||''}}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="所属平台" prop="payNo">
            <template slot-scope="scope">
              <div>{{ dict.platformType[scope.row.platformType] }}</div>
            </template>
          </el-table-column>
          <el-table-column label="库存更新比例" prop="payNo">
            <template slot-scope="scope">
              <div>{{ scope.row.stockProportion }}%</div>
            </template>
          </el-table-column>
          <el-table-column label="授权时间" prop="latestAuthorityTime"></el-table-column>
          <el-table-column label="操作" align="right" fixed="right" v-if="(loginMemberId && shopType == 1) || (this.getEnterpriseId() && shopType == 2)">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="doEdit(scope.row)">编辑</el-button>
              <el-popconfirm
                title="您确定删除吗？"
                @onConfirm="doDelete(scope.row.thirdShopId)"
              >
                <el-button slot="reference" class="mar-l-10" type="text">删除</el-button>
              </el-popconfirm>
              <el-button type="text" size="medium" @click="openUserPermitDialog(scope.row)" v-if="platformType === 3 || platformType === 4 || platformType === 5">消息权限开通</el-button>
              <el-button v-if="platformType == 1" type="text" size="medium" @click="doOpenAddress(scope.row)">地址列表</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 店铺信息dialog -->
    <el-dialog title="店铺信息" :visible.sync="thirdShopVisible" width="500px">
      <el-form :model="thirdShopForm" ref="thirdShopForm" :rules="rules" class="pad-10">
        <el-form-item label-width="120px" label="店铺所属平台：" prop="platformType">
          {{ dict.platformType[thirdShopForm.platformType] }}
        </el-form-item>
        <el-form-item label-width="120px" label="店铺ID：" prop="shopId">
          {{ thirdShopForm.shopId }}
        </el-form-item>
        <el-form-item label-width="120px" label="店铺名称：" prop="shopName">
          <span v-if="platformType == 3 || platformType == 5">{{ thirdShopForm.shopName }}</span>
          <el-input v-else class="width-300" v-model="thirdShopForm.shopName"></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="店铺网址：">
          <el-input class="width-300" v-model="thirdShopForm.shopUrl"></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="库存更新比例：">
          <el-slider v-model="thirdShopForm.stockProportion" :format-tooltip="formatTooltip" show-input input-size="mini"></el-slider>
        </el-form-item>
        <el-form-item label-width="30px" prop="timerLength">
          <el-checkbox v-model="thirdShopForm.stockFreqFlag" true-label="1" false-label="0">启动自动更新库存，每
            <el-input class="width-300" type="number" v-model="thirdShopForm.timerLength" style="width: 100px" min="0" max="59"></el-input>
            分钟更新一次</el-checkbox>
          <div class="font-10">(启用自动更新前，请先手动下载一次商品，<span class="font-red">注意：授权已过期的店铺忽略不自动更新商品库存，需要手动更新</span>)</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="thirdShopVisible = false">取消</el-button>
        <el-button type="primary" @click="doSave">保存</el-button>
      </div>
    </el-dialog>

    <!-- 地址列表dialog -->
    <el-dialog title="店铺发货/售后地址" :visible.sync="addressVisible" width="900px">
      <div class="margin-container-list">
        <div class="mar-b-20">
          <el-button type="primary" @click="doSyncAddress">同步地址</el-button>
        </div>
        <div class="table-container scroll-layer-box">
          <el-table :data="addressList" v-loading="listLoading" element-loading-text="加载中">
            <el-table-column min-width="300px" label="地址">
              <template slot-scope="scope">
                <span>{{ scope.row.receiver_provinc }}</span>
                <span>{{ scope.row.receiver_city }}</span>
                <span>{{ scope.row.receiver_district }}</span>
                <span>{{ scope.row.receiver_street }}</span>
                <span>{{ scope.row.receiver_detail }}</span>
              </template>
            </el-table-column>
            <el-table-column width="200px" label="联系人" prop="reciever_name"></el-table-column>
            <el-table-column width="120px" label="发货默认地址" prop="sellPrice">
              <template slot-scope="scope">
                <span>{{ scope.row.is_send_default === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column width="140px" label="退货默认地址" prop="externalCode">
              <template slot-scope="scope">
                <span>{{ scope.row.is_default === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 消息权限开通dialog -->
    <el-dialog title="消息权限开通" :visible.sync="userPermitVisible" width="500px">
      <el-form :model="userPermitForm" ref="userPermitForm" :rules="rules" class="pad-10">
        <el-form-item label-width="120px" label="消息权限: " prop="platformType">
          {{ userPermitCheckResult }}
        </el-form-item>
        <el-form-item label-width="120px" label="淘宝会员名称: " v-show="platformType === 3 || platformType === 5">
          <el-input class="width-300" v-model="userPermitForm.shopName"></el-input>
        </el-form-item>
        <el-form-item label-width="20px" v-show="platformType === 3 || platformType === 5">
          <span style="font-size: 11px; color: red">ps: 由于淘系API,都是以会员名称来通讯,为了保证以后接口通讯成功,淘系店铺名称必须是会员名称</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userPermitVisible = false">取消</el-button>
        <el-button type="primary" @click="userPermit">开通权限</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import thirdAuth from './components/third-auth'
  import thirdPlatformHead from './components/third-platform-head'
  import { pageThirdShop, saveThirdShop, deleteThirdShop, checkUserPermit, userPermit } from '@/api/user/third-shop'
  import { syncShopAddress } from '@/api/third/douYin'

  export default {
    components: { thirdPlatformHead },
    mixins: [thirdAuth],
    data() {
      return {
        // 默认查询条件
        defaultQuery: {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getMemberId(),
          currentPage: 1,
          size: 10,
          shopName: ''
        },
        // 查询条件
        searchListQuery: {},
        // 第三方店铺表单
        thirdShopForm: {
          thirdShopId: '',
          shopId: '',
          shopName: '',
          shopType: '',
          shopUrl: '',
          enterpriseId: '',
          platformType: '',
          stockFreqFlag: '0',
          timerLength: 0,
          stockProportion: ''
        },
        userPermitForm: {
          shopName: '',
          shopId: '',
          platformType: ''
        },
        // 数据字典
        dict: {
          platformType: {}
        },
        // 校验规则
        rules: {
          timerLength: [
            { required: true, message: '请填写分钟数', trigger: 'blur' },
            { pattern: /^[1-5]?[0-9]$/, message: '请填写0~59分钟区间的数' }
          ]
        },
        // 店铺类型
        shopType: '',
        // 平台类型
        platformType: 1,
        // 登录会员id
        loginMemberId: this.getMemberId(),
        // 回调地址
        redirectUrl: '',
        total: 0,
        dataList: [],
        addressList: [],
        selectedRow: '',
        listLoading: false,
        addressVisible: false,
        thirdShopVisible: false,
        userPermitVisible: false,
        userPermitCheckResult: ''
      }
    },
    // 初始化页面
    created() {
      this.searchListQuery = { ...this.defaultQuery }
      this.shopType = this.loginMemberId ? '1' : '2'
      this.redirectUrl = this.shopType === '1' ? '/#/shop/member/list' : '/#/channel/platform/list'
      const queryParams = this.getCurrentPage().query
      if (queryParams.platformType) {
        this.platformType = queryParams.platformType * 1
      }
      this.initList()
    },
    methods: {
      // 初始化
      initList() {
        this.searchListQuery.platformType = this.platformType
        this.searchListQuery.shopType = this.shopType
        this.listLoading = true
        pageThirdShop(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.dict = response.data.dict
        })
      },
      // 平台类型切换事件
      platformTypeChange(platformType) {
        this.platformType = platformType
        this.initList()
      },
      // tab切换事件
      doChangeTab() {
        this.doSearch()
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        this.searchListQuery = { ... this.defaultQuery }
        this.initList()
      },
      // 添加店铺事件
      doAddShop() {
        const platformType = this.platformType * 1
        const redirectUrl = this.redirectUrl + '?platformType=' + platformType
        this.authByPlatform(platformType, redirectUrl)
      },
      // 编辑事件
      doEdit(row) {
        this.thirdShopVisible = true
        Object.assign(this.thirdShopForm, row)
        this.thirdShopForm.stockFreqFlag = this.thirdShopForm.stockFreqFlag.toString()
      },
      // 保存事件
      doSave() {
        this.$refs['thirdShopForm'].validate((valid) => {
          if (valid) {
            saveThirdShop(this.thirdShopForm).then(response => {
              if (response.isError) return
              this.$message({ message: '保存成功！', type: 'success' })
              this.thirdShopVisible = false
              this.initList()
            })
          }
        })
      },
      // 删除事件
      doDelete(thirdShopId) {
        this.$confirm('删除店铺信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteThirdShop(thirdShopId).then(response => {
            if (response.isError) return
            this.$message({ message: '删除成功！', type: 'success' })
            this.initList()
          })
        }).catch(() => {
        })
      },
      formatTooltip(val) {
        return val + '%'
      },
      // 打开地址列表
      doOpenAddress(row) {
        this.addressList = []
        this.selectedRow = row
        this.addressVisible = true
      },
      // 同步地址事件
      doSyncAddress() {
        this.listLoading = true
        syncShopAddress(this.selectedRow.thirdShopId).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.addressList = response.data
          this.$message({ message: '同步成功', type: 'success' })
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      },
      // 抖音/淘宝消息权限开通
      openUserPermitDialog(row) {
        if (!row.shopId) {
          this.$message({ message: '未选择店铺', type: 'success' })
          return
        }
        this.userPermitVisible = true
        this.userPermitForm.shopId = row.shopId
        this.userPermitForm.shopName = row.shopName
        checkUserPermit(row.shopId, this.platformType).then(response => {
          if (response.isError) return
          this.userPermitCheckResult = response.data ? '开通' : '未开通'
        })
      },
      userPermit() {
        if (!this.userPermitForm.shopName) {
          this.$message({ message: '淘宝会员名称未填写', type: 'success' })
          return
        }
        userPermit(this.userPermitForm.shopId, this.platformType, this.userPermitForm.shopName).then(response => {
          if (response.isError) return
          this.$message({ message: '权限开通成功', type: 'success' })
          setTimeout(() => {
            location.reload()
          }, 1000)
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
</style>
